package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Setmeal;
import com.itheima.service.*;
import com.itheima.utils.DateUtils;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;
    @Reference
    private OrderService orderService;
    @Reference
    private OrderSettingService orderSettingService;

    // /report/getMemberReport
    // 折线图报表   返回 Map<String,List>
    @RequestMapping("/report/getMemberReport")
    public Result getMemberReport() {
        List<Integer> list2 = new ArrayList<>();
        List<String> list1 = new ArrayList<>();
        try {
            Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
            Date lastMonth1 = ca.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            ca.setTime(new Date());
            for (int i = 1; i <= 12; i++) {
                ca.add(Calendar.MONTH, -1);
                ca.set(Calendar.DAY_OF_MONTH, ca.getActualMinimum(Calendar.DAY_OF_MONTH));
                Date lastMonth = ca.getTime();
                String formatDate = sdf.format(lastMonth);
                int index1 = formatDate.lastIndexOf("-");
                list1.add(formatDate.substring(0, index1));
            }
            list2 = reportService.getMemberReport(list1);
            Map<String, List> map = new HashMap<>();
            map.put("months", list1);
            map.put("memberCount", list2);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }


    // /report/getSetmealReport
    // 饼状图   返回Map<String,List<Map<String,String>>
    @RequestMapping("/report/getSetmealReport")
    public Result getSetmealReport() {
        try {
            // 查询所有的 套餐
            List<Setmeal> setmeals = reportService.getSetmeal();
            List<String> setmealNames = new ArrayList<>();
            for (Setmeal setmeal : setmeals) {
                setmealNames.add(setmeal.getName());
            }
            // 查询所有预约套餐对应的数据
            List<Map<String, String>> setmealCount = reportService.getBySetmealIdOrderCount(setmeals);
            Map<String, List> map = new HashMap<>();
            map.put("setmealNames", setmealNames);
            map.put("setmealCount", setmealCount);
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    //  /report/getBusinessReportData
    // 运营数据统计
    @RequestMapping("/report/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //每日预约、到诊数量数据统计
    @RequestMapping("/report/getOrderReport")
    public Result getOrderReport() {
        Map<String, Object> map = new HashMap<>();
        try {
            List<String> months = new ArrayList<>();
            //获得日历对象，模拟时间就是当前对象
            Calendar calendar = Calendar.getInstance();
            //计算当前时间前后一个月
            calendar.add(Calendar.DATE, -31);//获得当前时间往前排一个月的时间
            for (int i = 0; i < 31; i++) {
                calendar.add(Calendar.DATE, 1);//获得当前时间往后推一个月的时间
                Date date = calendar.getTime();
                months.add(new SimpleDateFormat("yyyy.MM.dd").format(date));
            }
            map.put("months", months);

            List<Integer> orderCount = orderSettingService.findOrderCountByMonths(months);
            List<Integer> orderStatusCount = orderService.findOrderStatusCountByMonths(months);
            List<Integer> notOrderStatusCount = orderService.findNotOrderStatusCountByMonths(months);
            map.put("orderCount", orderCount);
            map.put("orderStatusCount", orderStatusCount);
            map.put("notOrderStatusCount", notOrderStatusCount);

            return new Result(true, MessageConstant.GET_ORDER_DAY_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_ORDER_DAY_REPORT_FAIL);
        }
    }

    //根据日期控件查询每日预约、到诊数量数据统计
    @RequestMapping("/report/getOrderDayReport")
    public Result getOrderDayReport(String[] value) {
        Map<String, Object> map = new HashMap<>();
        try {
            String begin = value[0];
            String end = value[1];
            //获得日历对象，模拟时间就是当前对象
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            calendar.setTime(sdf.parse(begin));
            List<String> months = new ArrayList<>();
            //遍历开始日期和结束日期的中间日期
            for (long d = calendar.getTimeInMillis(); d <= sdf.parse(end).getTime(); d = getAddDay(calendar)) {
                String month = sdf.format(d);
                months.add(month);
            }
            map.put("months", months);

            List<Integer> orderCount = orderSettingService.findOrderCountByMonths(months);
            List<Integer> orderStatusCount = orderService.findOrderStatusCountByMonths(months);
            List<Integer> notOrderStatusCount = orderService.findNotOrderStatusCountByMonths(months);
            map.put("orderCount", orderCount);
            map.put("orderStatusCount", orderStatusCount);
            map.put("notOrderStatusCount", notOrderStatusCount);

            return new Result(true, MessageConstant.GET_ORDER_DAY_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_ORDER_DAY_REPORT_FAIL);
        }
    }

    public static long getAddDay(Calendar calendar) {
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
        return calendar.getTimeInMillis();
    }

    //体检收入统计
    @RequestMapping("/report/getIncomeReport")
    public Result getIncomeReport() {
        Map<String, Object> data = new HashMap<>();
        try {
            //获得日历对象，模拟时间就是当前对象
            Calendar end = Calendar.getInstance();
            end.setTime(new Date());
            Date endTime = end.getTime();
            String endDay = new SimpleDateFormat("yyyy.MM.dd").format(endTime);//结束日期
            //计算当前时间往前一个月
            Calendar begin = Calendar.getInstance();
            begin.add(begin.DAY_OF_MONTH, -31);//获得当前时间往前排一个月的时间
            Date beginTime = begin.getTime();
            String beginDay = new SimpleDateFormat("yyyy.MM.dd").format(beginTime);//开始日期

            Map<String, String> mapDay = new HashMap<>();
            mapDay.put("begin", beginDay);
            mapDay.put("end", endDay);

            List<Map<String, Object>> setmealCount = setmealService.findSetmealIncome(mapDay);

            List<String> setmealNames = new ArrayList<>();
            List<Double> setmealIncome = new ArrayList<>();
            Map<String, Object> map1 = new HashMap<>();
            for (Map<String, Object> map : setmealCount) {
                String name = (String) map.get("name");//套餐名称
                setmealNames.add(name);

                Double price = (Double) map.get("value");//收入
                setmealIncome.add(price);
            }
            setmealNames.add("总收入");
            Double prices = 0d;
            for (Double aDouble : setmealIncome) {
                prices += aDouble;
            }
            map1.put("name", "总收入");
            map1.put("value", prices);
            setmealCount.add(map1);

            data.put("setmealIncome", setmealCount);
            data.put("setmealNames", setmealNames);

            return new Result(true, MessageConstant.GET_REPORT_INCOME_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_REPORT_INCOME_FAIL);
        }
    }

    //体检收入统计
    @RequestMapping("/report/getIncomeDayReport")
    public Result getIncomeDayReport(String[] value) {
        Map<String, Object> data = new HashMap<>();
        try {
            Map<String, String> mapDay = new HashMap<>();
            mapDay.put("begin", value[0]);
            mapDay.put("end", value[1]);
            List<Map<String, Object>> setmealCount = setmealService.findSetmealIncome(mapDay);

            List<String> setmealNames = new ArrayList<>();
            List<Double> setmealIncome = new ArrayList<>();
            Map<String, Object> map1 = new HashMap<>();
            for (Map<String, Object> map : setmealCount) {
                String name = (String) map.get("name");//套餐名称
                setmealNames.add(name);

                Double price = (Double) map.get("value");//收入
                setmealIncome.add(price);
            }
            setmealNames.add("总收入");
            Double prices = 0d;
            //遍历收入,获取总收入
            for (Double aDouble : setmealIncome) {
                prices += aDouble;
            }
            map1.put("name", "总收入");
            map1.put("value", prices);
            setmealCount.add(map1);

            data.put("setmealIncome", setmealCount);
            data.put("setmealNames", setmealNames);

            return new Result(true, MessageConstant.GET_REPORT_INCOME_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_REPORT_INCOME_FAIL);
        }
    }

    //年龄统计
    @RequestMapping("/report/getMemberAgeReport")
    public Result getMemberAgeReport() {
        try {
            //调用sql语句将用户存入集合中
            List<Member> members = memberService.findAll();
            //
            List<Integer> ages = new ArrayList<>();
            for (Member member : members) {
                //获取用户生日
                Date birthday = member.getBirthday();
                int age = DateUtils.getAgeByBirth(birthday);
                ages.add(age);
            }
            System.out.println(ages);
            //婴幼儿
            Integer infant = 0;
            //少儿
            Integer children = 0;
            //青少年
            Integer adolescent = 0;
            //青年
            Integer youth = 0;
            //中年
            Integer midlife = 0;
            //老年
            Integer oldMan = 0;
            for (Integer age : ages) {
                if (age >= 0 && age <= 6) {
                    infant++;
                } else if (age > 6 && age <= 12) {
                    children++;
                } else if (age > 12 && age <= 17) {
                    adolescent++;
                } else if (age > 17 && age <= 45) {
                    youth++;
                } else if (age > 45 && age <= 69) {
                    midlife++;
                } else if (age > 69) {
                    oldMan++;
                }
            }
            List<Integer> list = new ArrayList<>();
            list.add(infant);
            list.add(children);
            list.add(adolescent);
            list.add(youth);
            list.add(midlife);
            list.add(oldMan);

            return new Result(true, MessageConstant.GET_REPORT_AGE_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_REPORT_AGE_FAIL);
        }
    }

    // /report/exportBusinessReport
    // 运营数据报表导出
    @RequestMapping("/report/exportBusinessReport")
    public Result exportBusinessReport (HttpServletRequest resp, HttpServletResponse response){
            try {
                //上一次已经将数据查好并且封装到了Map集合中
                Map<String, Object> result = reportService.getBusinessReportData();

                String reportDate = (String) result.get("reportDate");
                Integer todayNewMember = (Integer) result.get("todayNewMember");
                Integer totalMember = (Integer) result.get("totalMember");
                Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
                Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
                Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
                Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
                Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
                Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
                Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
                Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
                List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

                // 获取 文件的绝对路径
                // File.separator 相当于动态的 \（/）
                String temlateRealPath = resp.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";

                XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(temlateRealPath)));
                // 读取第一个工作表
                XSSFSheet sheet = workbook.getSheetAt(0);

                System.out.println(workbook);
                System.out.println(sheet);


                //获取第二行
                XSSFRow row = sheet.createRow(2);
                System.out.println(row);
                System.out.println(row.getCell(5));

                row.createCell(5).setCellValue(reportDate);


                row = sheet.getRow(4);
                row.createCell(5).setCellValue(todayNewMember);//新增会员数（本日）
                row.createCell(7).setCellValue(totalMember);//总会员数

                row = sheet.getRow(5);
                row.createCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
                row.createCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

                row = sheet.getRow(7);
                row.createCell(5).setCellValue(todayOrderNumber);//今日预约数
                row.createCell(7).setCellValue(todayVisitsNumber);//今日到诊数

                row = sheet.getRow(8);
                row.createCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
                row.createCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

                row = sheet.getRow(9);
                row.createCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
                row.createCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

                int rowNum = 12;
                for (Map map : hotSetmeal) {//热门套餐
                    BigDecimal proportion = (BigDecimal) map.get("proportion");
                    String name = (String) map.get("name");
                    Long setmeal_count = (Long) map.get("setmeal_count");
                    row = sheet.getRow(rowNum++);
                    row.createCell(4).setCellValue(name);//套餐名称
                    row.createCell(5).setCellValue(setmeal_count);//预约数量
                    row.createCell(6).setCellValue(proportion.doubleValue());//占比
                }

                //下载表格 使用输出流进行表格下载
                //通过响应对象进行获得，将表对准客户端浏览器
                OutputStream os = response.getOutputStream();

                //  application/vnd.ms-excel 代表向客户端声明 输出的是 excel文件
                response.setContentType("application/vnd.ms-excel");
                //指定 以附件的形式下载
                response.setHeader("content-Disposition", "attachment;filename=report.xlsx");

                //通过 excel 文件中的 write 方法将流写道前端
                workbook.write(os);
                os.flush();
                os.close();
                workbook.close();

                return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
            }
        }

    // /report/exportBusinessReport1
    // 运营数据报表导出（PDF）导出
    @RequestMapping("/report/exportBusinessReport1")
    public Result exportBusinessReport1 (HttpServletRequest resp, HttpServletResponse response){
            try {
                //上一次已经将数据查好并且封装到了Map集合中
                Map<String, Object> result = reportService.getBusinessReportData();

                List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

                // 获取模板文件的路径
                String jrxmlPath = resp.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
                String jasperPath = resp.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";
                JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);

                // 循环填充数据
                JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath,
                        result,
                        new JRBeanCollectionDataSource(hotSetmeal));
                //下载表格 使用输出流进行表格下载
                //通过响应对象进行获得，将表对准客户端浏览器
                OutputStream os = response.getOutputStream();

                //  application/vnd.ms-excel 代表向客户端声明 输出的是 PDF 文件
                response.setContentType("application/pdf");
                //指定 以附件的形式下载
                response.setHeader("content-Disposition", "attachment;filename=report.pdf");

                //JasperExportManager 提供了一个文件，进行文件的输出
                JasperExportManager.exportReportToPdfStream(jasperPrint, os);

                return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
            }

        }
}